CommonUtils.regNamespace("com.im.roleManage");

com.im.roleManage.invoke = function () {
    var client = new com.im.common.ajax();
    var roleparam = {"pageInfo":{"pageSize":20,"pageNumber":1}};
    var role;//操邹的组织
    var operType;
    var statusCd;
    var configFuncMenus;
    var rolecolumns = [[
        {field:'checkRow',title:"选择",width:100,fitColumns:true,checkbox : true  },
        {
            field: 'roleId', title: "序号",width:$(this).width()*0.03, fitColumns: true,
            formatter: function (value, row, index) {
                return (index + 1);
            }
        },
        {field: 'name', title: "角色名称",width:$(this).width()*0.2, fitColumns: true},
        {field: 'statusName', title: "角色状态", width:$(this).width()*0.15,fitColumns: true},
        {field: 'description', title: "角色描述",width:$(this).width()*0.2, fitColumns: true},
        {field: 'createDt', title: "创建时间",width:$(this).width()*0.2, fitColumns: true},
        {
            field: 'operation', title: "操作",width:$(this).width()*0.14, fitColumns: true,
            formatter: function (value, row, index) { 
                return '<a href="javascript:;" onclick="com.im.roleManage.invoke.modifyRole(\'' + index + '\',\'modifyMenu\')" title="设置菜单"><i class="fa fa-cog"></i></a>' +
                    '<a href="javascript:;" onclick="com.im.roleManage.invoke.modifyRole(\'' + index + '\',\'modify\')" title="修改"><i class="fa fa-edit"></i></a>' +
                    '<!--<a href="javascript:;" onclick="com.im.roleManage.invoke.modifyRole(\'' + index + '\',\'del\')" title="删除"><i class="fa fa-trash"></i></a>-->';
            }
        }
    ]];

    function _init() {
        //查询角色 data-toggle="modal" data-target="#AddEditModal"
        //查询角色列表
        _queryRolesPage();

        //查询按钮
        $("#searchRoleBtn").click(function () {
            _queryRolesPage();
        });

        //新增
        $("#addRoleBtn").click(function () {
            operType = 'add';
            _showRoleInfo();
            $("#AddEditModal").modal('show');
        });

        //确认
        $("#ensureBtn").click(function () {
            _addOrUpdateRole();
        });

        //直接调用show看动态加载模态框不能显示出来
        $('#setMenuModal').on('shown.bs.modal', function () {
            $("#menuManageTree").empty();
            _showRoleMenus();
        });
        //菜单修改确认
        $("#menuEnsureBtn").click(function(){
            _modifyFuncMenu();
        });
        //
        $("#batchDelBtn").click(function () {
            _batchUpadateOrg("batchdel");
        });
        //用户状态
        $('#statusCdTxt').switchbutton({
            checked: true,
            onChange: function(checked){
                if (checked == true){
                    statusCd = '10';
                    roleparam.statusCd = statusCd;
                    roleparam.pageInfo.pageNumber =1;
                    _queryRolesPage();
                }
                if (checked == false) {
                    statusCd = '20';
                    roleparam.statusCd = statusCd;
                    roleparam.pageInfo.pageNumber =1;
                    _queryRolesPage();
                }}
        });
    }
    function _modifyFuncMenu(){
        var funcMenus = [];
        //获取现有
        var checkList = $("#menuManageTree").tree('getChecked', ['checked', 'indeterminate']);
        //对比原有
        //删除
        $.each(role.hasList,function(i,hobj){
            var ifhas = false;
            $.each(checkList,function(j,cobj){
                if(hobj.id == cobj.id){
                    //如果存在相等
                    ifhas = true;
                    return false;
                }
            });
            //不存在，那么删除了
            if(!ifhas){
                var delFuncMenu = {};
                delFuncMenu.roleId = role.roleId;
                delFuncMenu.funcMenuId = hobj.id;
                delFuncMenu.operType = 'del';
                funcMenus.push(delFuncMenu);
            }
        });
        //新增
        $.each(checkList,function(i,cobj){
            var ifhas = false;
            $.each(role.hasList,function(i,hobj){
                if(cobj.id == hobj.id){
                    ifhas = true;
                    return false;
                }
            });
            //不存在，那么新增
            if(!ifhas){
                var delFuncMenu = {};
                delFuncMenu.roleId = role.roleId;
                delFuncMenu.funcMenuId = cobj.id;
                delFuncMenu.operType = 'add';
                funcMenus.push(delFuncMenu);

            }
        });

        if(funcMenus.length > 0){
            var param = {};
            param.funcMenus = funcMenus;
            var result = client.callAsJson("userService/saveOrUpdateRole", param);
            if (result.success) {
                toastr.info("操作成功！");
            } else {
                toastr.error("服务器忙！请稍后再试！" + result.resultMsg);
            }

        }
        $("#setMenuModal").modal('hide');

    };
    function _addOrUpdateRole() {
        if(operType == 'modifyMenu'){

        }else{
            var roleName = $("#roleNameTxt").val();
            if (roleName == '' || roleName == undefined) {
                toastr.error("角色名称不能为空");
                return;
            }
            var description = $("#descriptionTxt").val();
            var param = {};
            var r = {};
            r.name = roleName;
            r.description = description;
            r.operType = operType;
            if (operType != 'add') {
                r.roleId = role.roleId;
            }
            param.role = r;
            var result = client.callAsJson("userService/saveOrUpdateRole", param);
            if (result.success) {
                $("#AddEditModal").modal('hide');
                toastr.info("操作成功！");
                roleparam.pageInfo.pageNumber = 1;
                _queryRolesPage();
            } else {
                toastr.error("服务器忙！请稍后再试！" + result.resultMsg);
            }
        }
    }


    function _modifyRole(idx, type) {
        operType = type;
        role = $('#roleListTb').datagrid('getData').rows[idx];
        if (operType == 'add') {
            $("#myModalLabel1").html("新增角色");
            $("#AddEditModal").modal('show');
        }
        if (operType == 'modify') {
            $("#myModalLabel1").html("修改角色");
            _showRoleInfo();
            $("#AddEditModal").modal('show');
        }
        if (operType == 'del') {
            $("#myModalLabel1").html("删除角色");
            _showRoleInfo();
            $("#AddEditModal").modal('show');
        }
        if (operType == 'modifyMenu') {
            $("#setMenuModal").modal('show');
        }
    };

    function _showRoleInfo() {
        if (operType == 'add') {
            $("#roleNameTxt").val('');
            $("#descriptionTxt").val('');
        } else {
            $("#roleNameTxt").val(role.name);
            $("#descriptionTxt").val(role.description);
        }

    };

    function _showRoleMenus() {
        //查询总菜单
        if(configFuncMenus == undefined || configFuncMenus == null){
            var qparam = {};
            qparam.forEasyUiTree = 'Y';
            var result = client.callAsJson("userService/queryFuncMenusByCond", qparam);
            if (result.success) {
                configFuncMenus = result.result;
            }else{
                configFuncMenus = [];
            }
        }
        //过滤一遍数据查询角色包含菜单
        var qparam = {};
        qparam.roleId = role.roleId;
        qparam.noSort = 'Y';//不排序
        var result = client.callAsJson("userService/queryFuncMenusByCond", qparam);
        var hasList = [];
        if (result.success) {
            hasList = result.result;
            $.each(configFuncMenus,function(i,obj){

                //循环子菜单
                $.each(obj.children,function(k,subobj){

                    var ifhas = false;
                    //已经存在的权限
                    $.each(hasList,function(j,hbobj){
                        if (hbobj.funcMenuId == subobj.id) {
                            ifhas = true;
                            return false;
                        }
                    });
                    if(ifhas){
                        //如果包含，默认选中
                        subobj.checked = true;
                    }else{
                        subobj.checked = false;
                    }
                    
                });
            });
        }
        //当前对象已有数组设置
        role.hasList = hasList;

        $("#menuManageTree").tree({
            data: configFuncMenus,
            onCheck : function (node) {//单击事件 选择
                //_treeOnClick(node,func,opt);
            }
        });

    };

    function _queryRolesPage() {
        $("#roleListTb").empty();
        roleparam.roleName = $("#roleName").val();
        var result = client.callAsJson("userService/queryConfigRolesByCond", roleparam);
        if (result.success) {
            $("#roleListTb").datagrid({
        	    nowrap:false,
        	    fitColumns:true,
                columns: rolecolumns,
                data: result.result
            });

            //页码
            $("#page").pagination({
                total : result.result.total,
                pageSize : result.result.pageSize,
                pageNumber : result.result.pageNumber,
                pageList : [20 , 40],
                beforePageText:  '第' ,
                afterPageText: '页 共'+result.result.totalPages+'页',
                displayMsg: '共 '+result.result.total+'条记录',
                onSelectPage: function (pageNumber, pageSize) {
                    roleparam.pageInfo.pageNumber = pageNumber;
                    roleparam.pageInfo.pageSize = pageSize;
                    _queryRolesPage();
                }
            });
        } else {
            toastr.error("服务器忙！请稍后再试！" + result.resultMsg);
        }
    }
    function _batchUpadateOrg(type){

        var nowlist = $("#roleListTb").datagrid('getChecked');
        if(nowlist != undefined && nowlist.length > 0){
            var msgStr = "确认批量失效"+nowlist.length+"个角色么？";
            if(statusCd == '20'){
                type = "batcheff";
                var msgStr = "确认批量生效"+nowlist.length+"个角色么？";
            }
            com.im.common.confirm(msgStr,{},function(){
                var roleList = [];
                $.each(nowlist,function (i,obj) {
                    roleList.push(obj.roleId);
                });
                var result = client.callAsJson("userService/saveOrUpdateRole", {roleList : roleList ,batchOperType : type});
                if(result.success){
                    toastr.info("操作成功！");
                    roleparam.pageInfo.pageNumber = 1;
                    _queryRolesPage();
                }else{
                    toastr.error("服务器忙，请稍后再试！"+result.resultMsg);
                }
            });
        }
    }
    return {
        init: _init,
        modifyRole: _modifyRole
    }

}();

$(function () {
    com.im.roleManage.invoke.init();
});